package com.cuoyi.coupon.mall.controller;

import com.cuoyi.coupon.mall.common.ApiResult;
import com.cuoyi.coupon.mall.common.Entry;
import com.cuoyi.coupon.mall.enums.ErrorEnum;
import com.cuoyi.coupon.mall.model.req.LoginReq;
import com.cuoyi.coupon.mall.service.UserService;
import com.cuoyi.coupon.mall.utils.JWTUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author zhang.cheng
 * 2022/3/23 9:43 PM
 */
@RestController
@Api(value = "登陆接口", tags = "登陆接口")
@RequestMapping(value = Entry.ADMIN)
public class LoginController {

    private static final Integer TOKEN_EXPIRE = 24 * 60 * 60;

    @Resource
    private UserService userService;

    @GetMapping(value = "/logout")
    public ApiResult logout() {
        return ApiResult.ok("登出成功！");
    }

    @PostMapping(value = "/login")
    public ApiResult login(@Valid @RequestBody LoginReq loginReq) {
        boolean result = userService.verifyLoginUser(loginReq.getUsername(), loginReq.getPassword());
        if (result) {
            String token = JWTUtils.createToken(loginReq.getUsername(), TOKEN_EXPIRE);
            return ApiResult.ok(token);
        }
        return ApiResult.error(ErrorEnum.PARAMS_ERROR.code(), "用户名密码不正确");
    }
}
